package com.lebang.controller.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lebang.common.util.PointUitl;
import com.lebang.component.RedisClient;
import com.lebang.component.UMengPushComponent;
import com.lebang.domain.TbTaskShanhuRecord;
import com.lebang.entity.PointwallRecord;
import com.lebang.entity.RequestHeaders;
import com.lebang.entity.TbTaskAotian;
import com.lebang.entity.member.LbbMember;
import com.lebang.entity.task.TaskXianwan;
import com.lebang.model.*;
import com.lebang.model.enums.buss.RewardType;
import com.lebang.model.enums.buss.TaskCategory;
import com.lebang.model.ywhz.YwhzModel;
import com.lebang.service.*;
import com.lebang.service.buss.MemberService;
import com.lebang.service.sdk.impl.MgddServiceImpl;
import com.lebangweb.common.TextUtil;
import com.lebangweb.encrypt.MessageDigestUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.*;

import static com.lebang.model.enums.buss.TaskCategory.*;
import static java.math.BigDecimal.ROUND_DOWN;

/**
 * 积分墙
 *
 * @author weizx
 * @className PointWallApi
 * @date 2018年8月14日 下午5:36:02
 */
@CrossOrigin
@RestController
public class PointWallApi {
    @Autowired
    private SdkVideoService sdkService;
    private static final Logger log = LoggerFactory.getLogger(PointWallApi.class);
    //闲玩KEY
    @Value("${info.sdk.xianwan}")
    private String KEY;
    //傲天KEY
    @Value("${info.sdk.aotian}")
    private String AOTIAN_KEY;
    //pc蛋蛋想玩
    @Value("${info.sdk.pcegg}")
    public String PCDDXW_KEY;
    //91淘金KEY
    @Value("${info.sdk.taojin}")
    private String TAOJIN_KEY;
    //乐享多游
    @Value("${info.sdk.lexiangduoyou}")
    private String LEXIANG_KEY;
    //聚享玩
    @Value("${info.sdk.juxiangwan}")
    public String JU_XIANG_WAN_KEY;
    //穿山甲视频
    @Value("${info.sdk.csjsp}")
    public String CSJ_KEY;
    //天卓珊瑚
    @Value("${info.sdk.tzsh}")
    public String TZ_SH;
    //鱼丸盒子
    @Value("${info.sdk.ywhz}")
    public String YW_HZ;
    //蛋蛋赚
    @Value("${info.sdk.dandanzhuan}")
    public String DANDANZHUAN;
    @Autowired
    private PointWallSdkService pointWallSdkService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private MemberNewTaskService taskService;
    @Autowired
    private RedisClient redisClient;
    public static final String LOCK = "lock:JU_XIANG_WAN_KEY:";
    @Autowired
    private TaskInRedisService taskInRedisService;

    @Autowired
    private MgddServiceImpl mgddService;
    @Autowired
    private PointService pointService;
    @Autowired
    private UMengPushComponent uMengPushComponent;
    @Autowired
    private DownAppService downAppService;
    @Autowired
    private TaskShanHuService taskShanHuService;
    @Autowired
    private PointWallSdkService videoService;
    @Autowired
    private MemberNoticeService memberNoticeService;



    @GetMapping("/wall/xianwan")
    public Map<String, Object> xianwan(Integer adid, String adname, String appid, String ordernum, Integer dlevel,
                                       String pagename, String deviceid, String simid,
                                       String appsign, String merid, String event,
                                       String price, String money, String itime, String keycode) {

        String allParam = adid + appid + ordernum + dlevel + deviceid + appsign + price + money + KEY;
        String sign = null;
        try {
            sign = MessageDigestUtil.encryptMD5(allParam.getBytes()).toUpperCase();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map map = new HashMap(1);
        if (!sign.equals(keycode.toUpperCase())) {
            map.put("success", 0);
            map.put("message", "签名无效");
            return map;
        }
        if (TextUtil.isEmpty(ordernum)) {
            map.put("success", 0);
            map.put("message", "订单为空");
            return map;
        }
        int i = pointWallSdkService.getByOrderNum(ordernum);
        if (i > 0) {
            map.put("success", 1);
            map.put("message", "订单已接收");
            return map;
        }
        LbbMember member = memberService.selectMemberById(appsign);
        if (member == null) {
            map.put("success", 0);
            map.put("message", "用户不存在");
            return map;
        }
        BigDecimal customPrice;
        BigDecimal userMoney;
        try {
            customPrice = new BigDecimal(price).setScale(2);
            userMoney = new BigDecimal(money).setScale(2);
            TaskXianwan taskXianwan = new TaskXianwan();
            taskXianwan.setAdName(adname);
            taskXianwan.setAdId(adid);
            taskXianwan.setAppId(appid);
            taskXianwan.setOrderNum(ordernum);
            taskXianwan.setDlevel(dlevel);
            taskXianwan.setPageName(pagename);
            taskXianwan.setDeviceId(deviceid);
            taskXianwan.setSimId(simid);
            taskXianwan.setMemberId(member.getMemberId());
            taskXianwan.setMerId(merid);
            taskXianwan.setEvent(event);
            taskXianwan.setPrice(customPrice);
            taskXianwan.setMoney(userMoney);
            taskXianwan.setiTime(itime);
            taskXianwan.setCreateTime(new Date());
            taskXianwan.setModifyTime(new Date());
            boolean wh = pointWallSdkService.xianwan(taskXianwan, member.getMemberId(), userMoney.multiply(new BigDecimal(100)).setScale(2).intValue());
            if (wh) {
                taskService.pushRecord(XianWan, member.getMemberId());
                map.put("success", 1);
                map.put("message", "接受成功");
                return map;
            } else {
                map.put("success", 0);
                map.put("message", "接受失败");
                return map;
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
            map.put("success", 0);
            map.put("message", "金额异常");
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            map.put("success", 0);
            map.put("message", "未知异常");
            map.put("obj", e);
            return map;
        }

    }


    @PostMapping("/wall/aotian")
    public String aoTian(HttpServletRequest request,
                         @RequestBody AotianModelRequest model) {
        try {
            String allParam = model.getCpl_id() + model.getOrder_id() + model.getAccount() + model.getCategory() + model.getMoney()
                    + model.getScalar() + model.getTime() + "@" + AOTIAN_KEY;
            String sign = null;
            try {
                sign = MessageDigestUtil.encryptMD5(allParam.getBytes()).toUpperCase();
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (!sign.equals(model.getSign().toUpperCase())) {
                return "签名错误!";
            }
            LbbMember member = memberService.selectMemberById(model.getAccount());
            if (member == null) {
                return model.getAccount() + "用户不存在";
            }
            BigDecimal amout = new BigDecimal(model.getMoney());
            if (amout.compareTo(BigDecimal.ZERO) < 0) {
                return "金额非法";
            }
            if (pointWallSdkService.checkAotianOrder(model.getOrder_id())) {
                return "success";
            }
            TbTaskAotian aotian = model.init();
            if (aotian == null) {
                return "参数不能为空" + model;
            }
            aotian.setMoney(amout);
            boolean i = pointWallSdkService.aotian(aotian, aotian.getMoney().multiply(new BigDecimal(100)).setScale(2).intValue());
            if (i) {
                taskService.pushRecord(AoTian, member.getMemberId());
                return "success";
            } else {
                return "fail";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "服务器异常" + e;
        }
    }

    @GetMapping("/wall/pcdandanxiangwan")
    public Map<String, Object> pcdandanxiangwan(HttpServletRequest request, Integer adid, String adname, String pid, String ordernum, Integer dlevel,
                                                String pagename, String deviceid, String simid,
                                                String userid, String merid, String event,
                                                String price, String money, String itime, String ptype, String keycode, String awardtype) {

        String allParam = adid + pid + ordernum + deviceid + PCDDXW_KEY;
        String sign = null;
        try {
            sign = MessageDigestUtil.encryptMD5(allParam.getBytes()).toUpperCase();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map map = new HashMap(1);
        if (!sign.equals(keycode.toUpperCase())) {
            map.put("success", 0);
            map.put("message", "签名无效");
            return map;
        }
        if (TextUtil.isEmpty(ordernum)) {
            map.put("success", 0);
            map.put("message", "订单为空");
            return map;
        }
        boolean i = pointWallSdkService.getByOrderNum(ordernum, PCDANDAN);
        if (i) {
            map.put("success", 0);
            map.put("message", "订单已存在");
            return map;
        }
        LbbMember member = memberService.selectMemberById(userid);
        if (member == null) {
            map.put("success", 0);
            map.put("message", "用户不存在");
            return map;
        }
        BigDecimal userMoney;
        BigDecimal myMoney;
        try {
            userMoney = new BigDecimal(money);
            myMoney = new BigDecimal(price);
            PointwallRecord record = new PointwallRecord();
            record.setHasDeleted(Whether.NO.getDbIndex());
            record.setCreateTime(new Date());
            record.setModifyTime(new Date());
            record.setMoney(userMoney);
            record.setEvent(event);
            record.setMemberId(userid);
            record.setSdkId(PCDANDAN.name());
            record.setOrderNum(ordernum);
            record.setAppId("xianyu");
            record.setMyMoney(myMoney);
            record.setParam(JSON.toJSONString(request.getParameterMap()));
            boolean wh = pointWallSdkService.creatOrder(PCDANDAN, record, userMoney.multiply(new BigDecimal(100).setScale(0, ROUND_DOWN)).intValue());
            if (wh) {
                map.put("success", 1);
                map.put("message", "接受成功");
                return map;
            } else {
                map.put("success", 0);
                map.put("message", "接受失败");
                return map;
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
            map.put("success", 0);
            map.put("message", "金额异常");
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            map.put("success", 0);
            map.put("message", "未知异常");
            map.put("obj", e);
            return map;
        }

    }

    @PostMapping("/wall/91taojin")
    public String taojin(HttpServletRequest request, String ID, String MtIDUser, String IMEI, String MtId, String IDUser
            , String UserFee, String MtFee, String DoneTime, String IDTask, String Note, String ExtParams, String sign) {
        try {
            Note = URLDecoder.decode(Note, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return "fail";
        }
        String allParam = DoneTime + "#" + ExtParams + "#" + ID + "#" + IDTask + "#" + IDUser + "#" + IMEI + "#" + MtFee + "#" + MtIDUser + "#" + MtId + "#" + Note + "#" + UserFee + "#" + TAOJIN_KEY;
        String mysign = null;
        try {
            Base64.Encoder encoder = Base64.getEncoder();
            mysign = MessageDigestUtil.encryptMD5(encoder.encodeToString(allParam.getBytes()).getBytes()).toUpperCase();
        } catch (Exception e) {
            e.printStackTrace();
            return "签名无效";
        }
        if (!sign.toUpperCase().equals(mysign.toUpperCase())) {

            return "签名无效";
        }
        if (TextUtil.isEmpty(ID)) {

            return "订单为空";
        }
        boolean i = pointWallSdkService.getByOrderNum(ID, TAOJIN);
        if (i) {
            return "ok";
        }
        LbbMember member = memberService.selectMemberById(MtIDUser);
        if (member == null) {
            return "用户不存在";
        }
        BigDecimal userMoney;
        BigDecimal myMoney;
        try {
            userMoney = new BigDecimal(UserFee);
            myMoney = new BigDecimal(MtFee);
            PointwallRecord record = new PointwallRecord();
            record.setHasDeleted(Whether.NO.getDbIndex());
            record.setCreateTime(new Date());
            record.setModifyTime(new Date());
            record.setMoney(userMoney);
            record.setEvent(Note);
            record.setMemberId(MtIDUser);
            record.setSdkId(TAOJIN.name());
            record.setOrderNum(ID);
            record.setAppId("xianyu");
            record.setMyMoney(myMoney);
            record.setParam(JSON.toJSONString(request.getParameterMap()));
            boolean wh = pointWallSdkService.creatOrder(TAOJIN, record, userMoney.multiply(new BigDecimal(100)).setScale(0, ROUND_DOWN).intValue());
            if (wh) {
                return "ok";
            } else {
                return "接受失败";
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return "金额异常";
        } catch (Exception e) {

            return e.toString();
        }

    }

    @GetMapping("/wall/duoyou")
    public Map duoyou(HttpServletRequest request, int advert_id, String advert_name, String order_id, String created, String media_income
            , String member_income, String media_id, String user_id, String device_id, String content, String sign) {
        Map map = new HashMap();
        String code = "";
        try {
            String callbackParams = request.getQueryString();
            Map<String, String> demoMap = PointUitl.getParameter(callbackParams);
            String localSign = PointUitl.generateSignature(demoMap, LEXIANG_KEY);
            if (TextUtil.isEmpty(order_id)) {
                code = "400";
                map.put("status_code", code);
                return map;
            }
          //  System.out.println(localSign);
            //校验签名
            if (sign.equalsIgnoreCase(localSign)) {

                boolean i = pointWallSdkService.getByOrderNum(order_id, LEXIANG);
                if (i) {
                    code = "200";
                    map.put("status_code", code);
                    return map;
                }
                LbbMember member = memberService.selectMemberById(user_id);
                if (member == null) {
                    code = "400";
                    map.put("status_code", code);
                    return map;
                }
                BigDecimal userMoney;
                BigDecimal myMoney;
                userMoney = new BigDecimal(member_income);
                myMoney = new BigDecimal(media_income).add(userMoney);
                PointwallRecord record = new PointwallRecord();
                record.setHasDeleted(Whether.NO.getDbIndex());
                record.setCreateTime(new Date());
                record.setModifyTime(new Date());
                record.setMoney(userMoney);
                record.setEvent(content);
                record.setMemberId(user_id);
                record.setSdkId(LEXIANG.name());
                record.setOrderNum(order_id);
                record.setAppId("xianyu");
                record.setMyMoney(myMoney);
                record.setParam(JSON.toJSONString(request.getParameterMap()));
                boolean wh = pointWallSdkService.creatOrder(LEXIANG, record, userMoney.multiply(new BigDecimal(100)).setScale(0, ROUND_DOWN).intValue());
                if (wh) {

                    code = "200";
                    map.put("status_code", code);
                    return map;
                } else {

                    code = "400";
                    map.put("status_code", code);
                    return map;
                }
            } else {
                code = "403";
            }
        } catch (Exception e) {
            code = "400";
        }
        map.put("status_code", code);
        return map;
    }

    @PostMapping("/wall/juxiangwan")
    public String juxiangwan(HttpServletRequest request, String resource_id, String time, String mid, String prize_info, String sign
            , String adid, String device_code) {
        String uuid = UUID.randomUUID().toString();
        if (!redisClient.tryGetDistributedLock(LOCK + resource_id + ":" + prize_info, uuid, 5000)) {
            return "请求频繁";
        }
        String allParam = prize_info + mid + time + resource_id + JU_XIANG_WAN_KEY;
        String mysign = null;
        try {
            mysign = MessageDigestUtil.encryptMD5(allParam.getBytes()).toUpperCase();

            if (!sign.toUpperCase().equals(mysign.toUpperCase())) {

                return "签名无效";
            }
            List<JuXiangWanModel> list = JSON.parseArray(prize_info, JuXiangWanModel.class);
            if (list == null) {
                return "fail";
            }
            LbbMember member = memberService.selectMemberById(resource_id);
            if (member == null) {
                return "用户不存在";
            }
            int k = 0;
            for (Iterator<JuXiangWanModel> iterator = list.iterator(); iterator.hasNext(); ) {
                JuXiangWanModel vo = iterator.next();
                if (TextUtil.isEmpty(vo.getPrize_id())) {
                    continue;
                }
                boolean i = pointWallSdkService.getByOrderNum(vo.getPrize_id(), JUXIANGWAN);
                if (i) {
                    continue;
                }

                BigDecimal userMoney;
                BigDecimal myMoney;
                try {
                    userMoney = new BigDecimal(vo.getTask_prize());
                    myMoney = new BigDecimal(vo.getDeal_prize()).add(userMoney);
                    PointwallRecord record = new PointwallRecord();
                    record.setHasDeleted(Whether.NO.getDbIndex());
                    record.setCreateTime(new Date());
                    record.setModifyTime(new Date());
                    record.setMoney(userMoney);
                    record.setEvent(vo.getName() + ":" + vo.getTitle());
                    record.setMemberId(resource_id);
                    record.setSdkId(JUXIANGWAN.name());
                    record.setOrderNum(vo.getPrize_id());
                    record.setAppId("xianyu");
                    record.setMyMoney(myMoney);
                    record.setParam(JSON.toJSONString(vo));
                    boolean wh = pointWallSdkService.creatOrder(JUXIANGWAN, record, userMoney.multiply(new BigDecimal(100)).setScale(0, ROUND_DOWN).intValue());
                    if (wh) {
                        k++;
                        continue;
                    } else {

                        continue;
                    }
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                    return "fail";
                } catch (Exception e) {
                    return e.toString();
                }
            }
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
            return "签名无效";
        } finally {
            redisClient.releaseDistributedLock(LOCK + resource_id + ":" + prize_info, uuid);
        }
    }

    @GetMapping("/wall/chuanshanjia")
    public Map csj(HttpServletRequest request, String sign, String user_id, String trans_id, String reward_amount, String reward_name,
                   String extra) {
        Map map = new HashMap();
        MessageDigest messageDigest;
        String str = CSJ_KEY + ":" + trans_id;
        String encodestr = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(str.getBytes(StandardCharsets.UTF_8));
            encodestr = PointUitl.byte2Hex(messageDigest.digest());
        } catch (Exception e) {
            e.printStackTrace();
            map.put("isValid", false);
            return map;
        }
        if (encodestr.equals(sign)) {
            LbbMember member = memberService.selectMemberById(user_id);
            if (member == null) {
                map.put("isValid", true);
                return map;
            }
            boolean i = pointWallSdkService.getByOrderNum(trans_id, CHUANGSHANJIA);
            if (i) {
                map.put("isValid", true);
                return map;
            }
            if (sdkService.checkMaxVideoCount(user_id)) {
                map.put("isValid", true);
                return map;
            }
            int userMoney = pointWallSdkService.getMoneyByVideoCheck(user_id);
            BigDecimal myMoney;
            try {

                myMoney = BigDecimal.ZERO;
                PointwallRecord record = new PointwallRecord();
                record.setHasDeleted(Whether.NO.getDbIndex());
                record.setCreateTime(new Date());
                record.setModifyTime(new Date());
                record.setMoney(new BigDecimal(userMoney));
                record.setEvent("视频激励");
                record.setMemberId(user_id);
                record.setSdkId(CHUANGSHANJIA.name());
                record.setOrderNum(trans_id);
                record.setAppId("xianyu");
                record.setMyMoney(myMoney);
                record.setParam(JSON.toJSONString(request.getParameterMap()));
                boolean wh = pointWallSdkService.creatOrderByPoint(CHUANGSHANJIA, record, userMoney);
                if (wh) {
                    taskInRedisService.csjAdd(record.getMemberId(), videoService.getList());
                    map.put("isValid", true);
                    return map;
                } else {
                    map.put("isValid", false);
                    return map;
                }
            } catch (NumberFormatException e) {
                e.printStackTrace();
                map.put("isValid", false);
                return map;
            } catch (Exception e) {
                map.put("isValid", false);
                return map;
            }
        } else {
            map.put("isValid", false);
            return map;
        }
    }


    //AD_KEY是由幂动广告提供的key
    @PostMapping("/wall/mdgg")
    public Map processCallBack(String ocode, Integer cid, String cuid, String devid, String adid, String adname,
                               String pkg, Integer adtype, String time, String points, String sign, HttpServletRequest request, double uprice, double dprice) {
        Map map = new HashMap();
        // 1. 校验MD5数据内容
        String parameter = ocode + cid + cuid + devid + adid + adname + pkg + adtype + time + points + mgddService.getKey();
        // 小写比较
        String md5Result = null;
        Integer money;
        try {
            md5Result = MessageDigestUtil.encryptMD5(parameter.getBytes()).toLowerCase().substring(10, 20);
            money = Integer.parseInt(points);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("status", 0);
            map.put("msg", e);
            return map;
        }
        //参数错误
        if (ocode == null || sign == null || adtype == null) {
            map.put("status", 0);
            map.put("msg", "参数错误");
            return map;
        }
        // md5校对结果
        boolean md5flag = md5Result.equals(sign);
        //数据校验成功
        if (md5flag) {
            LbbMember member = memberService.selectMemberById(cuid);
            if (member == null) {
                map.put("status", 0);
                map.put("msg", "用户不存在");
                return map;
            }
            boolean i = mgddService.checkOrderNum(ocode);
            if (i) {
                taskService.pushRecord(MDGG, member.getMemberId());
                map.put("status", 1);
                map.put("msg", "成功");
                return map;
            }

            boolean wh = mgddService.insertOrder(ocode, RewardType.Point.getIndex(), money, adname, cuid, JSON.toJSONString(request.getParameterMap()), new BigDecimal(dprice));
            if (wh) {
                RequestHeaders requestHeaders = pointWallSdkService.getRequestHeaders(member.getMemberId());
                pointService.addPointBySdk(cuid, money, MDGG, adname, requestHeaders);
                uMengPushComponent.sendNoRead(MDGG.getTitle() + adname + "已完成", adname + ":获得" + points + "金币", cuid);
                map.put("status", 1);
                map.put("msg", "成功");
                return map;
            } else {
                map.put("status", 0);
                map.put("msg", "异常");
                return map;
            }
        } else {
            map.put("status", 0);
            map.put("msg", "签名错误");
            return map;
        }
    }

    @Transactional
    @PostMapping("/wall/tzsh")
    public JSONObject tzsh(HttpServletRequest request, String channel_id,
                           String account_id, String longin_key, String record, @RequestBody TzshParentModel data) {
        // log.info(request.getParameterMap().toString());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("time", System.currentTimeMillis() / 1000);
        //  log.info(record);
        try {
            List<TzshModel> tzshModels = data.getRecord();
            for (Iterator<TzshModel> iterator = tzshModels.iterator(); iterator.hasNext(); ) {
                TzshModel next = iterator.next();
                String mysign = next.getTask_id() + next.getOrder_id() + TZ_SH;
                String md5Result = MessageDigestUtil.encryptMD5(mysign.getBytes());
                if (!md5Result.equals(next.getSign())) {

                    jsonObject.put("code", 0);
                    jsonObject.put("msg", "签名错误");
                    jsonObject.put("data", null);
                    log.info("天卓签名错误");
                    return jsonObject;
                }
                downAppService.pushByOrderId(next.getOrder_id());
                TbTaskShanhuRecord record1 = new TbTaskShanhuRecord(next);
                taskShanHuService.insertModel(record1);
            }
            jsonObject.put("code", 0);
            jsonObject.put("msg", "");
            jsonObject.put("data", null);
            // log.info("天卓回调成功");
            return jsonObject;
        } catch (Exception e) {
            e.printStackTrace();

            jsonObject.put("code", 1);
            jsonObject.put("msg", "格式错误");
            jsonObject.put("data", e);
            log.info("天卓格式错误");
            return jsonObject;
        }

    }

    @PostMapping("/wall/ywhz")
    public JSONObject processCallBack(//新量象平台唯一订单号
                                      YwhzModel model,
                                      HttpServletRequest request) {
        JSONObject map = new JSONObject();
        // 1. 校验MD5数据内容
        String parameter = model.getRewardDataJson() + model.getTime() + YW_HZ;
        // 小写比较
        String md5Result = null;
        Integer money;
        try {
            md5Result = MessageDigestUtil.encryptMD5(parameter.getBytes()).toLowerCase();

        } catch (Exception e) {
            e.printStackTrace();
            map.put("code", 2);
            map.put("msg", e);
            return map;
        }

        // md5校对结果
        boolean md5flag = md5Result.equals(model.getSign().toLowerCase());
        //数据校验成功
        if (md5flag) {
            RewardDataJson json = JSON.parseObject(model.getRewardDataJson(), RewardDataJson.class);
            if (json == null) {
                map.put("code", 2);
                map.put("msg", "参数错误");
                return map;
            }
            LbbMember member = memberService.selectMemberById(json.getMediaUserId());
            if (member == null) {
                map.put("code", 2);
                map.put("msg", "用户不存在");
                return map;
            }
            boolean i = pointWallSdkService.getByOrderNum(model.getOrderNo(), TaskCategory.YW_HZ);
            if (i) {
                map.put("code", 1);
                map.put("msg", "已接收过了");
                return map;
            }
            BigDecimal userMoney;
            BigDecimal myMoney;
            userMoney = new BigDecimal(json.getUserCurrency());
            myMoney = new BigDecimal(json.getMediaMoney()).add(userMoney);
            PointwallRecord record = new PointwallRecord();
            record.setHasDeleted(Whether.NO.getDbIndex());
            record.setCreateTime(new Date());
            record.setModifyTime(new Date());
            record.setMoney(userMoney);
            record.setEvent(json.getRewardRule());
            record.setMemberId(member.getMemberId());
            record.setSdkId(TaskCategory.YW_HZ.name());
            record.setOrderNum(model.getOrderNo());
            record.setAppId("xianyu");
            record.setMyMoney(myMoney);
            record.setParam(JSON.toJSONString(request.getParameterMap()));
            boolean wh = pointWallSdkService.creatOrder(TaskCategory.YW_HZ, record, userMoney.multiply(new BigDecimal(100).setScale(0, ROUND_DOWN)).intValue());
            if (wh) {
                taskService.pushRecord(TaskCategory.YW_HZ, member.getMemberId());
                RequestHeaders requestHeaders = pointWallSdkService.getRequestHeaders(record.getMemberId());
                memberNoticeService.addNoticeAndPush(TaskCategory.YW_HZ.getTitle(), record.getEvent(), record.getMemberId(), requestHeaders);
                map.put("code", 0);
                map.put("msg", "success");
                return map;
            } else {
                map.put("code", 2);
                map.put("msg", "异常");
                return map;
            }
        } else {
            map.put("code", 2);
            map.put("msg", "签名错误");
            return map;
        }
    }


    //AD_KEY是由幂动广告提供的key
    @PostMapping("/wall/dandanzhuan")
    public Map processCallBack(String orderid, Integer cid, String cuid, String devid, String adname,
                               Integer atype, String time, String points, String sign, HttpServletRequest request,String plat_points) {
        Map map = new HashMap();
        // 1. 校验MD5数据内容
        String parameter = orderid + cid + cuid + devid + adname + time + points + atype + DANDANZHUAN;
        // 小写比较
        String md5Result = null;
        try {
            md5Result = MessageDigestUtil.encryptMD5(parameter.getBytes()).toLowerCase().substring(10, 20);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("status", 0);
            map.put("msg", e);
            return map;
        }
        //参数错误
        if (orderid == null || sign == null || atype == null) {
            map.put("status", 0);
            map.put("msg", "参数错误");
            return map;
        }
        // md5校对结果
        boolean md5flag = md5Result.equals(sign);
        log.info(md5Result+":---------"+sign);
        //数据校验成功
        if (md5flag) {
            LbbMember member = memberService.selectMemberById(cuid);
            if (member == null) {
                map.put("status", 0);
                map.put("msg", "用户不存在");
                return map;
            }
            boolean i = pointWallSdkService.getByOrderNum(orderid, DANDAN_ZHUAN);
            if (i) {
                taskService.pushRecord(DANDAN_ZHUAN, member.getMemberId());
                map.put("status", 1);
                map.put("msg", "成功");
                return map;
            }
            BigDecimal userMoney;
            BigDecimal myMoney;
            userMoney = new BigDecimal(points);
            myMoney = new BigDecimal(plat_points);
            PointwallRecord record = new PointwallRecord();
            record.setHasDeleted(Whether.NO.getDbIndex());
            record.setCreateTime(new Date());
            record.setModifyTime(new Date());
            record.setMoney(userMoney);
            record.setEvent(adname);
            record.setMemberId(cuid);
            record.setSdkId(DANDAN_ZHUAN.name());
            record.setOrderNum(orderid);
            record.setAppId("xianyu");
            record.setMyMoney(myMoney);
            record.setParam(JSON.toJSONString(request.getParameterMap()));
            boolean wh = pointWallSdkService.creatOrder(DANDAN_ZHUAN, record, userMoney.multiply(new BigDecimal(100)).setScale(0, ROUND_DOWN).intValue());
            if (wh) {
                taskService.pushRecord(DANDAN_ZHUAN, member.getMemberId());
                map.put("status", 1);
                map.put("msg", "成功");
                return map;
            } else {
                map.put("status", 0);
                map.put("msg", "异常");
                return map;
            }
        } else {
            map.put("status", 0);
            map.put("msg", "签名错误");
            return map;
        }
    }
}
